import Config from '../config/config.js'
import {
		store,
	} from '@/uni_modules/uni-id-pages/common/store.js'
const http = {
	get: function() {
		console.log('http get')
	},
	request: function(api,method, data, succ, fail, loading=true) {
		console.log("request ",loading)
		if (loading) {
			console.log("request with loading...",loading)
			uni.showLoading({
				title: "",
				complete: () => {
					this._request(api,method,data,succ,fail,()=>{
						uni.hideLoading()
					})
				}
			})
		}
		else{
			this._request(api,"POST",data,succ,fail)
		}

	},
	get: function(api, data, succ,fail) {
		this.request(api,"GET",data,succ,fail)
	},
	post: function(api, data, succ,fail,loading) {
		console.log("post ",loading)
		this.request(api,"POST",data,succ,fail,loading)
	},
	_sign() {
		let appKey = 'FUTU_API',
			appSec = 'ZGXB4EP2ATZUEWQEIQ6WMG4H1CECAWTS';
		let now = new Date();
		let timestamp = now.getTime() / 1000
		const crypto = require('crypto')
		const sign = crypto.createHash('md5').update(appKey + timestamp + appSec).digest('hex').toUpperCase()
		const uid = store.userInfo && store.userInfo._id ? store.userInfo._id : null
		return {
			"app-key": appKey,
			timestamp: timestamp,
			sign: sign,
			uid:uid
		}
	},
	_request(api, method, data, succ, fail,complete) {
		console.log('http ' + method, Config.root + api)
		uni.request({
			url: Config.root + api,
			header: this._sign(),
			data: data,
			method: method,
			success: (res) => {
				console.log(res);
				if (res.data && res.data.code === 0) {
					succ && succ(res.data.data )
				} else {
					uni.showToast({
						icon:'error',
						title: res.data.msg || '请求失败'
					})
				}
			},
			fail: (err) => {
				console.log(err);
				uni.showToast({
					icon:'error',
					title: '请求失败，请重试'
				})
				fail && fail(err)
			},
			complete: () => {
				complete && complete()
			}
		})
	}
}
export default http